package com.power.ding.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.plf.core.base.model.Ha_depart;
import com.plf.core.base.model.Ha_user;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.ding.dao.Di_deptDao;
import com.power.ding.dao.Di_userDao;
import com.power.ding.model.Di_dept;
import com.power.ding.model.Di_user;
import com.power.ding.model.Gzt_User;
import com.power.ding.model.pageInfo.Di_userPageInfo;
import com.power.ding.service.Di_userService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 *  用户信息业务层实现
 */
@Service
public class Di_userServiceImpl extends BaseServiceImpl implements Di_userService {

    @Resource
    private Di_userDao dao;
    @Resource
    private Di_deptDao di_deptDao;

    @Override
    public Di_user getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Di_user di_user) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (di_user.getPrimaryKey() != null) {
        	 Di_user di_userfDb = dao.findById(di_user.getPrimaryKey()).orElse(null);
             if(di_userfDb != null) {
                BeanUtils.copyProperties(di_user, di_userfDb);
                dao.save(di_userfDb);
                return;
             }
        }
        dao.save(di_user);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Di_user> findAll(Di_userPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Di_user> findAll() {
		return dao.findAll();
	}

	@Override
	public void saveAll(List<Di_user> list) {
		dao.saveAll(list);
	}

    @Override
    public List<Di_user> findUserByOrgId(String orgId) {
        Specification<Di_user> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("orgid"), orgId), criteriaBuilder.ge(root.get(
                        "rowState"), 0))
        ).getRestriction();

        return dao.findAll(specification);
    }

    @Override
    public List<Map<String,Object>>  findAllDeptUser() {
        return dao.findAllDeptUser();
    }

    @Override
    public Di_user getUserAndDeptById(String userid, Gzt_User gzt_user) {
        // 1. 查询用户信息
        Di_user user = this.getById(userid);
        Assert.notNull(user,"用户不能为空");
        // 1.1 没有查到自动注册 (以后再说)
        if(null != user) {
            // 2. 查询部门信息
            List<Di_dept> deptList = this.di_deptDao.queryListByUserid(userid);
            user.setDeptList(deptList);
        }
        // 2. 查询关联的审批端信息
        Map approveMap = this.dao.findHa_userByMobile(user.getMobile());
        if(!approveMap.isEmpty()) {
            Ha_user approveUser = JSON.parseObject(JSON.toJSONString(approveMap), Ha_user.class);
            List<Map> approveDeparList = this.di_deptDao.findHa_departByMobile(approveUser.getUserid());
            user.setApproveUser(approveUser);
            List<Ha_depart> ApproveDepar = JSON.parseArray(JSON.toJSONString(approveDeparList), Ha_depart.class);
            user.setApproveDepar(ApproveDepar);
        }
        return user;
    }

    /**
     * 通过电话号码查询对应的赣政通用户
     * @param phones
     * @return
     */
    @Override
    public List<Di_user> getUserByPhones(List<String> phones) {
        // 按照电话号码查询对应的赣政通用户
        if (CollUtil.isNotEmpty(phones)) {
            return dao.findUserByPhones(phones);
        }
        return Collections.emptyList();
    }

    @Override
    public Map<String, Object> getSysUserByPhones(String mobile) {
        Map<String, Object> user = dao.getSysUserByPhones(mobile);
        if(!user.entrySet().isEmpty()) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Object> getRelUserByMobile(String mobile) {
        Map<String, Object> user = dao.getRelUserByMobile(mobile);
        if(!user.entrySet().isEmpty()) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public List<Di_user> getUserByName(String userName) {
        return dao.getUserByUserName(userName);
    }

    @Override
    public Di_user getUserByAdid(String adid) {
        // 查询部门信息
        Di_user userObj = this.dao.getUserByAdid(adid);
        List<Di_dept> deptList = this.di_deptDao.queryListByUserid(userObj.getId());
        if(CollectionUtils.isEmpty(deptList)) {
            throw new RuntimeException("getUserByAdid 用户部门为空!");
        }
        userObj.setDeptList(deptList);
        return userObj;
    }

    @Override
    public Di_user getUserByDeptid(String deptid) {
        // 查询部门信息
        Di_user userObj = this.dao.getUserByDeptid(deptid);
        List<Di_dept> deptList = this.di_deptDao.queryListByUserid(userObj.getId());
        if(CollectionUtils.isEmpty(deptList)) {
            throw new RuntimeException("getUserByDeptid 用户部门为空!");
        }
        userObj.setDeptList(deptList);
        return userObj;
    }

    @Override
    public List<Di_user> findUserByIds(List<String> ids) {
        if (CollUtil.isNotEmpty(ids)) {
            return dao.findUserByIds(ids);
        }
        return Collections.emptyList();
    }
}
